<template>
  <el-dialog title="新增角色" :visible="showDialog" @close="close">
    <el-form ref="editRoleRef" :model="editRoleForm" :rules="editRules" label-width="120px">
      <el-form-item label="角色名称" prop="name">
        <el-input v-model.trim="editRoleForm.name" />
      </el-form-item>
      <el-form-item label="角色描述">
        <el-input v-model.trim="editRoleForm.description" />
      </el-form-item>
    </el-form>
    <!-- 底部 -->
    <el-row slot="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" @click="close">取消</el-button>
        <el-button size="small" type="primary" @click="editOK">确定</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { getRoleDetail, updateRole } from '@/api/setting'
import { mapGetters } from 'vuex'
export default {
  name: 'AddRole',
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    editId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      editRoleForm: {
        name: '', // 角色名称
        description: '' // 角色描述
      },
      editRules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }]
      }
    }
  },
  computed: {
    ...mapGetters['companyId']
  },
  watch: {
    editId: {
      handler: function(value) {
        if (value) {
          this.getEditRole()
        }
      },
      immediate: true
    }
  },
  methods: {
    // // 获取数据
    async getEditRole() {
      this.editRoleForm = await getRoleDetail(this.editId)
      // console.log(this.editRoleForm)
    },
    // 退出
    close() {
      this.editRoleForm = {
        name: '',
        description: ''
      }
      this.$emit('update:showDialog', false) // 关闭弹窗
      this.$refs.editRoleRef.resetFields() // 清空数据
    },
    // 编辑成功
    editOK() {
      this.$refs.editRoleRef.validate(async(valid) => {
        if (valid) {
          // 验证通过
          await updateRole({ ...this.editRoleForm, companyId: this.companyId })
          this.$emit('editSuccess') // 刷新数据
          this.close()
          this.$message.success('更新角色成功')
        } else {
          return this.$message.error('更新角色失败')
        }
      })
    }

  }
}
</script>

<style lang="less" scoped>

</style>
